package com.gupaoedu.vip.pattern.template.jdbctemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public abstract class JdbcTemplate {

    private DataSource dataSource;

    protected PreparedStatement pstm;

    public JdbcTemplate(DataSource dataSource){
        this.dataSource = dataSource;
    }

    public void excute(String sql,Object [] values){
        try {
            // TODO 获取连接
            Connection conn = this.getConnection();
            // TODO 编译语句集
            pstm = this.createPrepareStatement(conn,sql);
            // TODO 参数赋值
            this.excuteQuery(values);
            // TODO 执行语句集
            this.close(conn,pstm);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    protected void close(Connection conn,PreparedStatement pstm) throws Exception{
        conn.close();
        pstm.close();
    }

    protected void excuteQuery(Object [] values) throws Exception{
        for (int i = 0; i < values.length; i++) {
            pstm.setObject(i,values[i]);
        }
        pstm.executeQuery();
    }

    protected PreparedStatement createPrepareStatement(Connection conn, String sql){
        try {
            return conn.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    };

    private Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
